package com.atguigu.flink.chapter06.state.keyed;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;

/**
 * @Author lzc
 * @Date 2023/6/20 14:23
 */
public class ListStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 输出每个传感器最高的三个水位值
        
        env
            .socketTextStream("hadoop162", 8888)
            .map(new WaterSensorMapFunction())
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private ListState<Integer> top3VcState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    top3VcState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("top3Vc", Integer.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    /*
                    每来一条数据,然后把数据存入到状态中, 取出状态中的数据, 排序, top3
                    更新状态
                     */
                    //top3VcState.update(); // 覆盖操作
                    top3VcState.add(value.getVc());
                   
                    Iterable<Integer> it = top3VcState.get();
                    List<Integer> list = AtguiguUtil.toList(it);
//                    list.sort((o1, o2) -> o2.compareTo(o1));
                    list.sort(Comparator.reverseOrder());
    
                    if (list.size() > 3) {
                        list.remove(list.size() - 1);
                    }
                    
                    // 更新状态
                    top3VcState.update(list);
    
                    System.out.println(ctx.getCurrentKey() + "top3水位: " + list);
    
                    
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
listState.update(list 集合) 覆盖
listSate.get() 获取 list 状态的值
listSate.clear() 清空状态中的值
listState.add(单值) 向 list 状态中增加数据
listSate.addAll(list 集合); 把参数 list 集合的所有元素添加到状态中
 */